package com.hhkj.api.question.biz.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.hhkj.admin.question.domain.Question;
import com.hhkj.admin.question.service.base.ProblemFeedbackService;
import com.hhkj.admin.question.service.base.QuestionService;
import com.hhkj.api.question.biz.ApiProblemFeedbackBizService;
import com.hhkj.api.question.model.req.ApiProblemFeedbackSaveReq;
import com.ruoyi.common.core.domain.entity.SysDictData;
import com.ruoyi.common.core.mail.MailSenderService;
import com.ruoyi.system.service.ISysDictDataService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.concurrent.CompletableFuture;

/**
 * @Author luowu
 * @Date 2024/8/9 涵 14:38:36
 */
@Slf4j
@Service
public class ApiProblemFeedbackBizServiceImpl implements ApiProblemFeedbackBizService {

    @Resource
    private ProblemFeedbackService problemFeedbackService;

    @Resource
    private MailSenderService mailSenderService;

    @Resource
    private ISysDictDataService sysDictDataService;

    @Resource
    private QuestionService questionService;

    @Value("${spring.mail.text:用户反馈了一个题目异常，题目:（{}），错误类型：（{}），问题描述：（{}），请注意查看处理}")
    private String messageTip;


    @Override
    public boolean save(ApiProblemFeedbackSaveReq req) {
        boolean isSuccess = problemFeedbackService.save(req);
        // 异步发送邮件提醒
        CompletableFuture.runAsync(() -> afterSaveSendMail(req));
        return isSuccess;
    }

    /**
     * 保存成功后异步发送邮件提醒
     * @param req
     */
    public void afterSaveSendMail(ApiProblemFeedbackSaveReq req){
        try {
            SysDictData sysDictData = sysDictDataService.selectDictDataById(req.getMistakeType());
            // 题目类型
            String misTakeName = ObjectUtil.isNotNull(sysDictData) ? sysDictData.getDictLabel() : "未知类型";
            // 提问的题目
            Question question = questionService.getById(req.getQuestionId());
            // 题目内容
            String questionContent = ObjectUtil.isNotNull(question) ? question.getContent() : "未知题目";
            mailSenderService.sendSimpleEmail(StrUtil.format(messageTip, questionContent, misTakeName, req.getProblemDesc()));
        } catch (Exception e) {
            log.error("发送邮件异常", e);
        }
    }
}
